package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelDyUtil;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.MaterialInfojk;
import com.ruoyi.system.api.domain.ShCourseTeacher;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.ShBanner;
import com.ruoyi.system.service.IMaterialInfojkService;
import com.ruoyi.system.service.IShBannerService;
import com.ruoyi.system.service.IShCourseTeacherService;
import com.ruoyi.system.service.impl.InsertInfoTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@RestController
@RequestMapping("/infojk")
public class MaterialInfojkController extends BaseController {
    @Autowired
    private IMaterialInfojkService materialInfojkService;
    @Autowired
    private IShBannerService shBannerService;
    @Autowired
    private IShCourseTeacherService shCourseTeacherService;

    /**
     * 查询句块信息列表
     */
    @RequiresPermissions("system:infojk:list")
    @GetMapping("/list")
    public TableDataInfo list(MaterialInfojk materialInfojk)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfojk.setAppId(user.getAppId());
        }
        startPage();
        List<MaterialInfojk> list = materialInfojkService.selectMaterialInfojkList(materialInfojk);
        return getDataTable(list);
    }

    /**
     * 获取句块信息详细信息
     */
    @RequiresPermissions("system:infojk:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(materialInfojkService.selectMaterialInfojkById(id));
    }

    /**
     * 新增句块信息
     */
    @RequiresPermissions("system:infojk:add")
    @Log(title = "句块信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MaterialInfojk materialInfojk)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfojk.setAppId(user.getAppId());
        }
        MaterialInfojk param = new MaterialInfojk();
        param.setMaterialName(materialInfojk.getMaterialName());
        param.setAppId(user.getAppId());
        List<MaterialInfojk> list = materialInfojkService.selectMaterialInfojkList(param);
        if (null!=list&&list.size()>0) {
            return AjaxResult.error("新增句块'" + materialInfojk.getMaterialName() + "'失败，句块已存在");
        }
        return toAjax(materialInfojkService.insertMaterialInfojk(materialInfojk));
    }

    /**
     * 修改句块信息
     */
    @RequiresPermissions("system:infojk:edit")
    @Log(title = "句块信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MaterialInfojk materialInfojk)
    {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if (!SysUser.isAdmin(user.getUserId())) {
            materialInfojk.setAppId(user.getAppId());
        }
        return toAjax(materialInfojkService.updateMaterialInfojk(materialInfojk));
    }

    /**
     * 删除句块信息
     */
    @RequiresPermissions("system:infojk:remove")
    @Log(title = "句块信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(materialInfojkService.deleteMaterialInfojkByIds(ids));
    }

    @GetMapping("/importTemplate/{importType}/{id}")
    public void importTemplate(HttpServletResponse response, @PathVariable String importType, @PathVariable Long id) throws IOException
    {
        List<String> paramList = new ArrayList<>();
        String fileName = "";
        if ("banner".equals(importType)) {
            fileName = "公共句块";
            ShBanner banner = shBannerService.selectShBannerById(id);
            paramList.add(banner.getProductTitle()+"*");
        }else {
            fileName = "老师句块";
            ShCourseTeacher teacher = shCourseTeacherService.selectShCourseTeacherById(id);
            paramList.add(teacher.getTeacherName()+"*");
        }
        paramList.add("句块内容*");
        paramList.add("句块关键词*");
        paramList.add("是否免费*");
        paramList.add("收费金额*");
        paramList.add("所属年级");
        paramList.add("所属科目");
        paramList.add("所属年份");
        paramList.add("所属学期");
        byte[] bytes = ExcelDyUtil.exportExcelHead(paramList, "xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String filename = fileName+"导入模板.xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.getOutputStream().write(bytes);
    }

    @Log(title = "句块信息导入", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:infojk:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String fz) {
        try {
            ExcelUtil<MaterialInfojk> util = new ExcelUtil<MaterialInfojk>(MaterialInfojk.class);
            List<MaterialInfojk> infoList = util.importExcel(file.getInputStream());
            final Boolean[] endFlag = {false};
            final List<Integer> numTh = new ArrayList<>();
            final BlockingQueue<MaterialInfojk> results = new LinkedBlockingQueue<MaterialInfojk>();
            SysUser user = SecurityUtils.getLoginUser().getSysUser();
            ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    for (MaterialInfojk obj:infoList) {
                        results.add(obj);
                    }
                    Thread t = new Thread(r);
                    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e){
                        }
                    });
                    return t;
                }
            });
            InsertInfoTask t = new InsertInfoTask<MaterialInfojk>(results, endFlag, numTh, materialInfojkService, updateSupport, user, fz);
            Future<?> future = executorService.submit(t);
            executorService.shutdown();
            future.get();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            String msg = e.getMessage().substring(27);
            return AjaxResult.success(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }
}
